package com.situ.stmall.manger.interceptor;

import com.situ.stmall.manger.entity.Admin;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AdminTnterceptor implements HandlerInterceptor {
    /**
     * 执行拦截器之前执行，
     * 放行放回true，拦截放回false
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //return HandlerInterceptor.super.preHandle(request, response, handler);
        //验证登陆用户
        HttpSession session = request.getSession();//从request上获取session
        Admin admin =(Admin) session.getAttribute("admin");
        if(admin == null){
            //没有登陆，跳转到登陆页面
            response.sendRedirect("/admin/lgoin.html");
        }
        return true;
    }

    /**
     * 处理器处理完成后执行，视图解析器还没有执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 所有的处理都完成时执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
